﻿using DotNetMVC.OA.IBLL;
using DotNetMVC.OA.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DotNetMVC.OA.BLL
{
 public partial class ActionInfoService : BaseService<ActionInfo>, IActionInfoService
    {
        public IQueryable<ActionInfo> LoagPageData(Model.Param.ActionQueryParam actionQueryParam)
        {
            short normalFlag = (short)Model.Enum.DelFlagEnum.Normal;
            var temp = DbSession.ActionInfoDal.GetEntities(u=>u.DelFlag== normalFlag);

            //过滤权限名
            if (!string.IsNullOrEmpty(actionQueryParam.SchName))
            {
                temp=temp.Where(u=>u.ActionName.Contains(actionQueryParam.SchName));
            }
            //过滤备注
            if (!string.IsNullOrEmpty(actionQueryParam.SchRemark))
            {
                temp = temp.Where(u => u.Remark.Contains(actionQueryParam.SchRemark));
            }
            actionQueryParam.Total = temp.Count();
            //分页
            return temp.OrderBy(u => u.ID)
                .Skip(actionQueryParam.PageSize * (actionQueryParam.PageIndex - 1))
                .Take(actionQueryParam.PageSize);

        }

        /// <summary>
        /// 设置角色
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="roleIds"></param>
        /// <returns></returns>
        public bool SetRole(long actionId, List<long> roleIds)
        {
            short delFlagNormal = (short)Model.Enum.DelFlagEnum.Normal;
            //获取权限所有角色
            var rURs = DbSession.R_RoleInfo_ActionInfoDal.GetEntities(rUR => rUR.ActionInfoID == actionId && rUR.DelFlag == delFlagNormal);
            //遍历删除原有角色
            foreach (var rUR in rURs)
            {
                DbSession.R_RoleInfo_ActionInfoDal.Delete(rUR);
            }

            //获取选中权限
            var allRoles = DbSession.RoleInfoDal.GetEntities(r => roleIds.Contains(r.ID));
            foreach (var roleInfo in allRoles)
            {
                R_RoleInfo_ActionInfo model = new R_RoleInfo_ActionInfo();
                model.ActionInfoID = actionId;
                model.RoleInfoID = roleInfo.ID;
                //添加到权限角色关系表
                DbSession.R_RoleInfo_ActionInfoDal.Add(model);
            }
            DbSession.SaveChanges();

            return true;
        }
    }
}
